package com.xiyu.service.dal.websocket.receiveMail;

import com.xiyu.service.dal.websocket.receiveMail.message.ReceiveMailReceiveMessage;
import com.xiyu.service.enums.common.UserTypeEnum;
import com.xiyu.service.framework.exception.ServiceException;
import com.xiyu.service.framework.postOffice.factory.PostOfficeFactory;
import com.xiyu.service.framework.postOffice.service.PostOfficeService;
import com.xiyu.service.framework.websocket.core.listener.WebSocketMessageListener;
import com.xiyu.service.framework.websocket.core.sender.WebSocketMessageSender;
import com.xiyu.service.model.mailbox.account.MailboxAccount;
import com.xiyu.service.repository.mailbox.account.MailboxAccountRepository;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import jakarta.annotation.Resource;
import java.util.List;

import static com.xiyu.service.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

@Component
public class ReceiveMailWebSocketMessageListener implements WebSocketMessageListener<List<Long>> {
    @Resource
    private WebSocketMessageSender webSocketMessageSender;

    @Resource
    private PostOfficeFactory postOfficeFactory;

    @Resource
    private MailboxAccountRepository mailboxAccountRepository;

    final String socketType = "receive-mail";

    @Override
    public void onMessage(WebSocketSession session, List<Long> accountIds) {
        String currentAccountName = "";
        try {
            for(Long accountId : accountIds){
                MailboxAccount account = mailboxAccountRepository.findNullable(accountId);
                currentAccountName = account.showName();
                PostOfficeService postOfficeService = postOfficeFactory.getInstance(accountId);
                postOfficeService.receiveAccountMail();
            }
            ReceiveMailReceiveMessage toMessage = new ReceiveMailReceiveMessage("任务成功完成", "done", "");
            webSocketMessageSender.sendObject(UserTypeEnum.ADMIN.getValue(), getLoginUserId(),  socketType, toMessage);
        }catch (ServiceException e){
            ReceiveMailReceiveMessage toMessage = new ReceiveMailReceiveMessage(e.getMessage(), "error", currentAccountName);
            webSocketMessageSender.sendObject(UserTypeEnum.ADMIN.getValue(), getLoginUserId(),  socketType, toMessage);
        }
    }

    @Override
    public String getType() {
        return socketType;
    }

}
